package view;

import app.App;
import component.CustomJTable;
import model.Product;
import model.SaleRecord;
import model.User;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StatisticsPane {
    private JTabbedPane tabbedPane1;
    private JPanel contentPane;
    private JPanel chartPanel1;
    private JPanel chartPanel2;
    private JTable table_saleRecordList;
    private JButton btn_refresh_list;
    private JButton btn_refresh_chart;

    JFreeChart chartStaffSaleStatics;
    JFreeChart chartProductSaleStatics;
    DefaultPieDataset<String> dataset1;
    DefaultPieDataset<String> dataset2;

    DefaultTableModel tableModel_saleRecordList;

    private void createUIComponents() {
        App.currentSaleRecordList = SaleRecord.getSaleRecordList();

        table_saleRecordList = new CustomJTable(new String[]{"流水号","收银员","商品号","商品名","售价","数量","总金额","时间"});
        tableModel_saleRecordList = (DefaultTableModel) table_saleRecordList.getModel();

        dataset1 = createStaffSaleStaticsDS(App.currentSaleRecordList);
        chartStaffSaleStatics = createPieChart("员工销售统计", dataset1);
        chartPanel1 = new ChartPanel(chartStaffSaleStatics);
        ((ChartPanel)chartPanel1).setMouseWheelEnabled(true);

        dataset2 = createStaffSaleStaticsDS(App.currentSaleRecordList);
        chartProductSaleStatics = createPieChart("商品销售统计", dataset2);
        chartPanel2 = new ChartPanel(chartProductSaleStatics);
        ((ChartPanel)chartPanel2).setMouseWheelEnabled(true);
    }

    public StatisticsPane() {
        notifySaleRecordListChanged();

        //刷新列表
        btn_refresh_list.addActionListener(e -> notifySaleRecordListChanged());
        //刷新图表
        btn_refresh_chart.addActionListener(e -> notifySaleRecordListChanged());
    }

    public JPanel getContentPane() {
        return contentPane;
    }

    public void notifySaleRecordListChanged() {
        App.currentSaleRecordList = SaleRecord.getSaleRecordList();

        tableModel_saleRecordList.setRowCount(0);
        System.out.println("销售历史列表更新：");
        List<SaleRecord> currentSaleRecord = App.currentSaleRecordList;
        if (currentSaleRecord != null) {
            //更新列表
            for (SaleRecord saleRecord : currentSaleRecord) {
                tableModel_saleRecordList.addRow(saleRecord.toSaleListObjectArray());
            }
            CustomJTable.resizeColumnWidth(table_saleRecordList);
            //更新员工销售统计图表
            dataset1 = createStaffSaleStaticsDS(currentSaleRecord);
            PiePlot<String> piePlot1 = (PiePlot<String>)chartStaffSaleStatics.getPlot();
            piePlot1.setDataset(dataset1);
            //更新商品销售统计图表
            dataset2 = createProductSaleStaticsDS(currentSaleRecord);
            PiePlot<String> piePlot2 = (PiePlot<String>)chartProductSaleStatics.getPlot();
            piePlot2.setDataset(dataset2);
        }

    }

    //计算员工销售统计数据集
    private DefaultPieDataset<String> createStaffSaleStaticsDS(List<SaleRecord> saleRecordList) {

        DefaultPieDataset<String> dataset = new DefaultPieDataset<>();
        //生成HashMap，以员工Id为key，销售金额为value
        Map<Integer, Float> map = new HashMap<>();
        for (SaleRecord saleRecord : saleRecordList) {
            if (map.containsKey(saleRecord.getCashier())) {
                //如果员工Id已存在，销售金额累加
                map.put(saleRecord.getCashier(), map.get(saleRecord.getCashier()) + (saleRecord.getSellingPrice() * saleRecord.getCount()));
            } else {
                //如果员工Id不存在，直接添加
                map.put(saleRecord.getCashier(), saleRecord.getSellingPrice() * saleRecord.getCount());
            }
        }
        //根据员工Id获取员工名
        Object[] keys_id = map.keySet().toArray();
        List<String> keys_name = new ArrayList<>();
        for (Object key : keys_id) {
            keys_name.add(User.getUser((Integer) key).getUserName());
        }

        //将员工名和销售金额逐个添加到dataset
        Object[] values = map.values().toArray();
        for (int i = 0; i < keys_name.size(); i++) {
            dataset.setValue(keys_name.get(i)+"( "+String.format("%.2f", values[i])+" 元)", (float)values[i]);
        }
        return dataset;
    }

    //计算商品销售统计数据集
    private DefaultPieDataset<String> createProductSaleStaticsDS(List<SaleRecord> saleRecordList) {

        DefaultPieDataset<String> dataset = new DefaultPieDataset<>();
        //生成HashMap，以商品Id为key，销售金额为value
        Map<Integer, Float> map = new HashMap<>();
        for (SaleRecord saleRecord : saleRecordList) {
            if (map.containsKey(saleRecord.getProductId())) {
                //如果商品Id已存在，销售金额累加
                map.put(saleRecord.getProductId(), map.get(saleRecord.getProductId()) + (saleRecord.getSellingPrice() * saleRecord.getCount()));
            } else {
                //如果商品Id不存在，直接添加
                map.put(saleRecord.getProductId(), saleRecord.getSellingPrice() * saleRecord.getCount());
            }
        }
        //根据商品Id获取商品名
        Object[] keys_id = map.keySet().toArray();
        List<String> keys_name = new ArrayList<>();
        for (Object key : keys_id) {
            keys_name.add(Product.getProduct((Integer) key).getProductName());
        }

        //将商品名和销售金额逐个添加到dataset
        Object[] values = map.values().toArray();
        for (int i = 0; i < keys_name.size(); i++) {
            dataset.setValue(keys_name.get(i)+"( "+String.format("%.2f", values[i])+" 元)", (float) values[i]);
        }
        return dataset;
    }

    private JFreeChart createPieChart(String title, DefaultPieDataset<String> dataset) {

        JFreeChart chart = ChartFactory.createPieChart(title, dataset, false, true, false);

        TextTitle textTitle = chart.getTitle();
        textTitle.setFont(new Font("微软雅黑", Font.BOLD, 20));

        PiePlot<String> plot = (PiePlot<String>) chart.getPlot();
        plot.setBackgroundPaint(null);
        plot.setInteriorGap(0.04);
        plot.setOutlineVisible(false);
        plot.setLabelFont(new Font("微软雅黑", Font.PLAIN, 14));

        return chart;
    }
}









